<?php

namespace User\Controller;

use Common\Controller\AdminbaseController;
use User\Model\AdminLevel;
use User\Model\User;
use User\Model\SmsLogModel;

class IndexadminController extends AdminbaseController
{
    private $user_model;

    public function __construct()
    {
        parent::__construct();
        $this->user_model = M( "user", 'system_', C( 'DB_CONFIG2' ) );
        $this->jum_url = 'http://127.0.0.1/';
    }
    protected $unapproved=[
        '0'=>'',
        '1'=>'通讯录低于40',
        '2'=>'手机卡实名不足半年',
        '3'=>'手机卡非本人实名',
        '4'=>'命中黑名单',
        '5'=>'芝麻分不符合（成人不能低于580）',
        '6'=>'年龄不符合（不能高于32岁）',
        '7'=>'地区不符合（学生：新疆西藏；成人：四川、新疆、西藏、内蒙古）',
        '8'=>'有当前逾期',
        '9'=>'资料不符合',
        '10'=>'负债不符合',
        '11'=>'未联系上客户',
        '12'=>'不愿意办理',
        '13'=>'客户不回复审核',
    ];
    /**
     * 后台本站用户列表
     */
    public function index()
    {
        $reflux_status = I('request.reflux_status');
        /**
         * $reflux_status：0回流状态 1正常 2审核成功
         */
        switch ($reflux_status){
            case '1':
                $wheres[] = 'reflux_status = 1';
                break;
            case '2':
                $wheres[] = 'reflux_status = 0';
                break;
            default:
                $wheres[] = '(reflux_status = 1 OR reflux_status = 0)';
        }
        //$this->show_user($where);//耦合的方法
        $request = I( 'request.' );
        $request['byusers'] = empty( $request['byusers'] ) ? 0 : $request['byusers'];
        switch($request['byusers']) {
            case '2':
                $group = get_groups_admin_user();
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers=' . get_current_admin_id();
                } else {
                    $wheres[] = 'a.byusers!="0"';
                }
                break;
            case '3':
                $group = get_groups_admin_user();
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers in (' . get_current_admin_id() . ',0)';
                }
                break;
            default:
                $wheres[] = 'a.byusers="0"';
        }
        $is_dis = true;
        $is_di = [];
        $request['is_dis'] = empty( $request['is_dis'] ) ? 0 : $request['is_dis'];
        switch($request['is_dis']) {
            case '2':
                $wheres[] = 'a.is_dis="1"';
                $is_dis = true;
                break;
            case '3':
                break;
            default:
                $wheres[] = 'a.is_dis="0"';
        }
        //资料认证状态
        $account_status = I('account_status',-1);
        $this->account_status = $account_status;
        if(-1!=$account_status && $account_status!='4' ) {
            $wheres[] = 'a.account_status='.$account_status;
        }
        if ($account_status=='4'){//除了已认证
            $wheres[] = 'a.account_status <> 1 and a.account_status <> 3';
        }
        if(!empty( $request['name'] )) {
            $wheres[] = 'a.name like "%' . $request['name'] . '%"';
        }
        if(!empty( $request['mobile'] )) {
            $wheres[] = 'a.mobile like "%' . $request['mobile'] . '%"';
        }
        if(!empty( $request['identity'] )) {
            $wheres[] = 'a.identity like "%' . $request['identity'] . '%"';
        }
        if(!empty( $request['starts'] )) {
            $wheres[] = 'a.crtime>="' . date( 'Y-m-d 00:00:00', strtotime( $request['starts'] ) ) . '"';
        }
        if(!empty( $request['ends'] )) {
            $wheres[] = 'a.crtime<="' . date( 'Y-m-d 23:59:59', strtotime( $request['ends'] ) ) . '"';
        }
        //借款状态：条件：
        if($request['type_borr'] != '' && in_array((int)$request['type_borr'],[0,1,2,3])) {
            $wheres[] = 'a.type_borr="' . $request['type_borr'] . '"';
        }
        //订单状态
        if(I('request.status')!==''){
            $wheres[] = 'o.status='.I('request.status');
        }
        if($request['type'] != '' && is_numeric($request['type'])) {
            $wheres[] = 'a.type="' . $request['type'] . '"';
        }
        if($name = I('request.qudao',0)){
            $ur = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->field( 'code' )->where( 'name like "%' . $name . '%"' )->select();
            if(!empty( $ur )) {
                $i = [];
                foreach($ur as $v) {
                    $i[] = "'".$v['code']."'";
                }
                $wheres[] = 'a.code in (' . implode( ',', $i ) . ')';
            }
        }
        $sql = 'SELECT count(a.id) as _cnt 
                FROM system_user a
                LEFT JOIN
                (
                SELECT id,user_id,`status` FROM orders WHERE id IN(SELECT MAX(id) AS id FROM orders GROUP BY user_id)
                ) o ON o.user_id=a.id
                WHERE ( '.implode( ' AND ', $wheres ).' ) LIMIT 1';
        $for_count = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->query($sql);
        $count = $for_count[0]['_cnt'];
        $page = $this->page( $count, 20 );

        $order = empty($order)?'a.modtime DESC,a.crtime DESC':$order;
        $sql = 'SELECT a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,a.code,a.reflux_status,o.status,o.amount,o.order_status,
                  a.accept_bind,a.borr_record,a.sesame_score,a.unapproved
                FROM system_user a 
                LEFT JOIN
                (
                SELECT id,user_id,`status`,`status` as order_status,amount FROM orders WHERE id IN(SELECT MAX(id) AS id FROM orders GROUP BY user_id)
                ) o ON o.user_id=a.id
                WHERE ( '.implode( ' AND ', $wheres ).' ) ORDER BY '.$order.' LIMIT '.$page->firstRow . ',' . $page->listRows;
        $list = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->query($sql);
        $ids = [];
        //关键他会问小新，叫我们两周开发(重构)一个项目也是小新的意见
        $codes = [];
        $num=[];
        foreach($list as $v) {
            if(!empty( $v['byusers'] )) {
                $ids[] = $v['byusers'];
            }
            if(!empty( $is_dis )) {
                $is_di[] = $v['id'];
            }
            if(!empty( $v['code'] )) {
                $codes[] = "'" . $v['code'] . "'";
            }
            if(is_numeric($v['mobile'])){
                $num[$v['mobile']]=$v['mobile'];
            }
        }
        if(!empty( $ids )) {
            $buyer = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            $buyers = [];
            foreach($buyer as $v) {
                $buyers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'buyers', $buyers );
        }
        if(!empty( $is_di )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'is_dis=1 and user_id in (' . implode( ',', $is_di ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['user_id']] = $v['code'];
            }
            $this->assign( 'is_dis', $is_ids );
        }
        if(!empty( $codes )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['code']] = $v['name'];
            }
            $this->assign( 'codes', $is_ids );
        }
        if(!empty($num)){
            $log=M( "log", 'sms_', C( 'DB_CONFIG2' ))->field('id,mobile')->where('mobile in ('.implode(',',$num).') and type=3')->select();
            $logs=[];
            foreach($log as $v){
                $logs[$v['mobile']]=$v['id'];
            }
            $this->assign( 'send_sms', $logs );
        }
        //获取审核用户
        $shen_user = M( "users" )->alias( "a" )->join( C( 'DB_PREFIX' ) . 'role_user as b on a.id =b.user_id' )->where( 'b.role_id in (3,8) and a.user_status=1' )->order( 'a.id desc' )->select();
        $this->assign( 'shen_user', $shen_user );
        $this->assign( 'wheres_str', json_encode($wheres) );
        $this->assign( 'list', $list );
        $this->assign( 'unapproved', $this->unapproved );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display( ":index" );
    }

    /**
     * 显示用户列表信息
     * @param array $wheres
     */
    function show_user($wheres=[],$order=''){
        $request = I( 'request.' );
        $request['byusers'] = empty( $request['byusers'] ) ? 0 : $request['byusers'];
        switch($request['byusers']) {
            case '2':
                $group = get_groups_admin_user();
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers=' . get_current_admin_id();
                } else {
                    $wheres[] = 'a.byusers!="0"';
                }
                break;
            case '3':
                $group = get_groups_admin_user();
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers in (' . get_current_admin_id() . ',0)';
                }
                break;
            default:
                $wheres[] = 'a.byusers="0"';
        }
        $is_dis = true;
        $is_di = [];
        $request['is_dis'] = empty( $request['is_dis'] ) ? 0 : $request['is_dis'];
        switch($request['is_dis']) {
            case '2':
                $wheres[] = 'a.is_dis="1"';
                $is_dis = true;
                break;
            case '3':
                break;
            default:
                $wheres[] = 'a.is_dis="0"';
        }
        //资料认证状态
        if(empty($where['account_status_str'])){
            $account_status = I('account_status',-1);
            $this->account_status = $account_status;
            if($account_status!='-1' && $account_status!='4' ) {
                $wheres[] = 'a.account_status='.$account_status;
            }
            if ($account_status=='4'){//除了已认证
                $wheres[] = 'a.account_status <> 1 and a.account_status <> 3';
            }
        }else{
            $wheres[] = $where['account_status_str'];
        }
        unset($where['account_status_str']);
        if(!empty( $request['name'] )) {
            $wheres[] = 'a.name like "%' . $request['name'] . '%"';
        }
        if(!empty( $request['mobile'] )) {
            $wheres[] = 'a.mobile like "%' . $request['mobile'] . '%"';
        }
        if(!empty( $request['identity'] )) {
            $wheres[] = 'a.identity like "%' . $request['identity'] . '%"';
        }
        if(!empty( $request['starts'] )) {
            $wheres[] = 'a.crtime>="' . date( 'Y-m-d 00:00:00', strtotime( $request['starts'] ) ) . '"';
        }
        if(!empty( $request['ends'] )) {
            $wheres[] = 'a.crtime<="' . date( 'Y-m-d 23:59:59', strtotime( $request['ends'] ) ) . '"';
        }
        if($request['type_borr'] != '' && is_numeric($request['type_borr'])) {
            $wheres[] = 'a.type_borr="' . $request['type_borr'] . '"';
        }
        if($request['type'] != '' && is_numeric($request['type'])) {
            $wheres[] = 'a.type="' . $request['type'] . '"';
        }
        $count = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->where( implode( ' and ', $wheres ) )->count( 'id' );
        $page = $this->page( $count, 20 );

        $order = empty($order)?['a.modtime' =>'DESC','a.crtime'=>'DESC']:$order;
        $list = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->where( implode( ' and ', $wheres ) )
            ->field( 'a.unapproved,a.mobile,a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,a.code,a.reflux_status' )
            //->field('a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,c.name as dis_name')
            //->join("LEFT JOIN system_distribution c on c.code=a.code")
            ->order( $order )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        $ids = [];
        $codes = [];
        foreach($list as $v) {
            if(!empty( $v['byusers'] )) {
                $ids[] = $v['byusers'];
            }
            if(!empty( $is_dis )) {
                $is_di[] = $v['id'];
            }
            if(!empty( $v['code'] )) {
                $codes[] = "'" . $v['code'] . "'";
            }
        }
        if(!empty( $ids )) {
            $buyer = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            $buyers = [];
            foreach($buyer as $v) {
                $buyers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'buyers', $buyers );
        }
        if(!empty( $is_di )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'is_dis=1 and user_id in (' . implode( ',', $is_di ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['user_id']] = $v['code'];
            }
            $this->assign( 'is_dis', $is_ids );
        }
        if(!empty( $codes )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['code']] = $v['name'];
            }
            $this->assign( 'codes', $is_ids );
        }
        //获取审核用户
        $shen_user = M( "users" )->alias( "a" )->join( C( 'DB_PREFIX' ) . 'role_user as b on a.id =b.user_id' )->where( 'b.role_id in (3,8) and a.user_status=1' )->order( 'a.id desc' )->select();
        $this->assign( 'shen_user', $shen_user );
        $this->assign( 'wheres_str', json_encode($wheres) );
        $this->assign( 'unapproved', $this->unapproved );
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
    }

    /**
     * 批量添加回流用户
     */
    public function batch_add_reflux_user(){
        $dt = I( 'post.id', 0 );
        $this->batch_update_reflux_status(0,$dt);
    }

    /**
     * 批量修改回流用户到正常状态
     * reflux_status 回流状态0回流1正常2审核成功
     */
    public function batch_update_reflux2normal(){
        $dt = I( 'post.id', 0 );
        $this->batch_update_reflux_status(1,$dt);
    }

    /**
     * 批量修改用户回流状态
     * @param $update_status 更新to状态
     * @param array $id_arr 用户Id数组
     */
    public function batch_update_reflux_status($update_status,$id_arr=[]){
        $user = $this->user_model
            ->where( 'id in (' . implode( ',', $id_arr ) . ')' )
            ->where( [ 'reflux_status' => [ 'neq', $update_status ] ] )
            ->field( 'id' )->select();
        if(empty( $user )) {
            $this->error( "选择的用户已存在正常用户中！" );
        }
        $ids = [];
        foreach($user as $v) {
            $ids[] = $v['id'];
        }
        if(0==$update_status){
            $save = [
                'reflux_status' => $update_status,
            ];
            $this->user_model->where( 'id in (' . implode( ',', $ids ) . ')' )->save( $save );
        }else{
            //当回流用户=>正常用户,已完善资料的用户更新资料更新时间
            $now_time = date('Y-m-d H:i:s',time());
            $sql = "UPDATE system_user 
              SET reflux_status = 1,
                  modtime = '".$now_time."'
              WHERE id IN (". implode( ',', $ids ) .");";
            $this->user_model->execute($sql);
        }
        $this->success( "添加成功！" );
    }

    /**
     * 回流用户
     */
    public function reflux_user(){
        $wheres[] = 'a.reflux_status = 0';
        $this->show_user($wheres);
        $this->display(':reflux_user');
    }
    /**
     * 不借列表
     */
    public function unwanted_user(){
        $wheres=[];
        $request = I( 'request.' );
        $request['byusers'] = empty( $request['byusers'] ) ? 0 : $request['byusers'];
        switch($request['byusers']) {
            case '2':
                $group = get_groups_admin_user();
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers=' . get_current_admin_id();
                } else {
                    $wheres[] = 'a.byusers!="0"';
                }
                break;
            case '3':
                $group = get_groups_admin_user();
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers in (' . get_current_admin_id() . ',0)';
                }
                break;
            default:
                //$wheres[] = 'a.byusers="0"';
        }
        $is_dis = true;
        $is_di = [];
        $request['is_dis'] = empty( $request['is_dis'] ) ? 0 : $request['is_dis'];
        switch($request['is_dis']) {
            case '2':
                $wheres[] = 'a.is_dis="1"';
                $is_dis = true;
                break;
            case '3':
                break;
            default:
                $wheres[] = 'a.is_dis="0"';
        }
        if(!empty( $request['name'] )) {
            $wheres[] = 'a.name like "%' . $request['name'] . '%"';
        }
        if(!empty( $request['mobile'] )) {
            $wheres[] = 'a.mobile like "%' . $request['mobile'] . '%"';
        }
        if(!empty( $request['identity'] )) {
            $wheres[] = 'a.identity like "%' . $request['identity'] . '%"';
        }
        if(!empty( $request['starts'] )) {
            $wheres[] = 'a.crtime>="' . date( 'Y-m-d 00:00:00', strtotime( $request['starts'] ) ) . '"';
        }
        if(!empty( $request['ends'] )) {
            $wheres[] = 'a.crtime<="' . date( 'Y-m-d 23:59:59', strtotime( $request['ends'] ) ) . '"';
        }
        if($request['type_borr'] != '' && is_numeric($request['type_borr'])) {
            $wheres[] = 'a.type_borr="' . $request['type_borr'] . '"';
        }
        if($request['type'] != '' && is_numeric($request['type'])) {
            $wheres[] = 'a.type="' . $request['type'] . '"';
        }
        if(!empty( $request['starts_zmf'] )) {
            $wheres[] = 'a.sesame_score>="' . $request['starts_zmf'] . '"';
        }
        if(!empty( $request['ends_zmf'] )) {
            $wheres[] = 'a.sesame_score<="' . $request['ends_zmf'] . '"';
        }
        $where=['1=1'];
        if(is_numeric($request['ordnum']) && $request['ordnum']>0){
            $where[] = 'a.renew="' . ($request['ordnum']-1) . '"';
            if(($request['ordnum']-1)!=1){
                //资料认证状态
                $wheres[] = 'a.account_status=2';
            }else{
                $wheres[] = 'a.type_borr!=2';
                $where[]='a.status=6';
            }
        }else{
            //资料认证状态
            $wheres[] = 'a.account_status = 2';
        }
        if(is_numeric($request['is_adult']) && $request['is_adult']>=0){
            $wheres[] = 'a.is_adult="' . $request['is_adult'] . '"';
        }
        $select='a.id';
        $sql='select count(a.id) as id from (select max(c.id),c.renew,c.status,'.$select.' from orders c ,(SELECT '.$select.' FROM system_user a WHERE ('.implode(' and ',$wheres).')) a where a.id=c.user_id GROUP BY c.user_id) a where '.implode(' and ',$where);
        $count=M("ders",'or',C('DB_CONFIG2'))->query($sql);
        $page = $this->page( $count[0]['id'], 20 );
        $order = ['a.modtime DESC','a.crtime DESC'];
//        $list = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->where( implode( ' and ', $wheres ) )
//            ->field( 'a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,a.code,a.reflux_status' )
//            //->field('a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,c.name as dis_name')
//            //->join("LEFT JOIN orders c on c.user_id=a.id")
//            ->order($order)
//            ->limit( $page->firstRow . ',' . $page->listRows )
//            ->select();
        $select='a.sesame_score,a.is_adult,a.modtime,a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,a.code,a.reflux_status';
        $sql='select a.renew,a.status,'.$select.' from (select max(c.id),c.renew,c.status,'.$select.' from orders c ,(SELECT '.$select.' FROM system_user a WHERE ('.implode(' and ',$wheres).')) a where a.id=c.user_id GROUP BY c.user_id) a where '.implode(' and ',$where).' ORDER BY '.implode(' , ',$order).' limit '.$page->firstRow . ',' . $page->listRows;
        $list=M("ders",'or',C('DB_CONFIG2'))->query($sql);
        $ids = [];
        $codes = [];
        foreach($list as $v) {
            if(!empty( $v['byusers'] )) {
                $ids[] = $v['byusers'];
            }
            if(!empty( $is_dis )) {
                $is_di[] = $v['id'];
            }
            if(!empty( $v['code'] )) {
                $codes[] = "'" . $v['code'] . "'";
            }
        }
        if(!empty( $ids )) {
            $buyer = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            $buyers = [];
            foreach($buyer as $v) {
                $buyers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'buyers', $buyers );
        }
        if(!empty( $is_di )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'is_dis=1 and user_id in (' . implode( ',', $is_di ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['user_id']] = $v['code'];
            }
            $this->assign( 'is_dis', $is_ids );
        }
        if(!empty( $codes )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['code']] = $v['name'];
            }
            $this->assign( 'codes', $is_ids );
        }
        //获取审核用户
        $shen_user = M( "users" )->alias( "a" )->join( C( 'DB_PREFIX' ) . 'role_user as b on a.id =b.user_id' )->where( 'b.role_id in (3,8) and a.user_status=1' )->order( 'a.id desc' )->select();
        $this->assign( 'shen_user', $shen_user );
        $wheres['other_where']=json_encode($where);
        $this->assign( 'wheres_str', json_encode($wheres) );
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display(':unwanted_user');
    }

    /**
     * @use          [运营登记]
     * @author       chenxiaogang
     */
    public function operator_remark()
    {
        $user_id = I('get.id',0,'int');
        if(empty($user_id)){
            $this->error("传输错误");
        }
        $recordModel = new \User\Model\UserRemarksModel();
        if(IS_GET){
           $user = $this->user_model->find($user_id);//用户信息
           $list = $recordModel->where(['user_id'=>$user_id])->select();//备注记录
           $adminIdsArr = array_column($list,'create_by');//取出所有登记人ID
           if(!empty($adminIdsArr)){
               $admins = D('Users')->where(['id'=>['in',$adminIdsArr]])->getfield('id,user_login');//取出登记人对应管理员名字列表
               $this->assign('admins',$admins);
           }
           $currentAdmin = D('Users')->field('user_login')->find(get_current_admin_id());//当前管理员
           $this->assign('currentAdmin',$currentAdmin);
           $this->assign('user',$user);
           $this->assign('list',$list);
           $this->display();
       }else{
           $data = [
               'user_id'=>$user_id,
               'remark'=>I('post.remark'),
               'create_time'=>time(),
               'create_by'=>get_current_admin_id(),
           ];
           $id = $recordModel->add($data);
           if($id>0){
               $this->success('新增成功',U('indexadmin/unwanted_user'));
           }else{
               $this->error('新增失败，请稍后再试');
           }
       }
    }

    /**
     * @use          [删除一条用户备注]
     * @author       chenxiaogang
     */
    public function del_user_remark()
    {
        $id = I('get.id',0,'int');
        if(empty($id)){
            $this->error('传输错误');
        }
        $recordModel = new \User\Model\UserRemarksModel();
        if($recordModel->delete($id)>0){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    
    /**
     * 导出本站用户
     */
    function export_app_user(){
        $wheres = I( 'get.wheres' );
        $wheres = htmlspecialchars_decode($wheres);
        $wheres=json_decode($wheres,true);
        if(in_array('a.account_status=1',$wheres)){
            $this->error('无法导出已认证客户!');
        }
        if(in_array('a.account_status=3',$wheres)){
            $this->error('无法导出暂时不需要的客户!');
        }
        $where=['1=1'];
        if(!empty($wheres['other_where'])){
            $where=json_decode($wheres['other_where'],true);
            unset($wheres['other_where']);
        }
        $select='a.id';
        $sql='select count(a.id) as id from (select max(c.id),c.renew,c.status,'.$select.' from orders c ,(SELECT '.$select.' FROM system_user a WHERE ('.implode(' and ',$wheres).')) a where a.id=c.user_id GROUP BY c.user_id) a where '.implode(' and ',$where);
        $count=M("ders",'or',C('DB_CONFIG2'))->query($sql);
        $order = ['a.modtime DESC','a.crtime DESC'];
        if($count[0]['id']>20000){
            $this->error('无法导出超过20000条以上数据!');
        }
        $user_model = new User();
        $mulit_arr = array(
            array("注册时间","姓名","资料审核状态","借款状态","年龄","资料认证状态","手机","微信","QQ","身份证","芝麻分"),
        );
        //列数,需要时再添加,避免多次循环
        $cell_title_arr = ['A','B','C','D','E','F','G','H','I','J','K'];
        $width_arr = [20,10,15,15,30,15,20,15,15,25,15];
        /* @实例化 */
        vendor('PHPExcel.PHPExcel');
        $obpe = new \PHPExcel();

        $step = 5000;
        for ($i=0; $i<$count[0]['id']; $i=$i+$step) {
            $select='a.mobile,a.qq,a.email,a.is_adult,a.modtime,a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,a.code,a.reflux_status,a.sesame_score';
            $sql='select a.renew,a.status,'.$select.' from (select max(c.id),c.renew,c.status,'.$select.' from orders c ,(SELECT '.$select.' FROM system_user a WHERE ('.implode(' and ',$wheres).')) a where a.id=c.user_id GROUP BY c.user_id) a where '.implode(' and ',$where).' ORDER BY '.implode(' , ',$order).' limit '.$i . ',' . $step;
            $list=M("ders",'or',C('DB_CONFIG2'))->query($sql);
            if($i!=0){
                $obpe->createSheet();
            }
            $obpe->setactivesheetindex($i);
            //写入多行数据
            array_unshift($list,$mulit_arr);
            foreach($list as $k=>$v){
                $k = $k+1;
                if($k==1){
                    /* @func 设置列-表头 */
                    foreach($cell_title_arr AS $ckey=>$cval){
                        $obpe->getactivesheet()->setcellvalue($cval.$k, $v[0][$ckey]);
                    }
                }else{
                    /* @func 设置列 */
                    $obpe->getactivesheet()->setcellvalue('A'.$k, $v['crtime']);
                    $obpe->getactivesheet()->setcellvalue('B'.$k, $v['name']);
                    $obpe->getactivesheet()->setcellvalue('C'.$k, $user_model::getUserTypeText($v['type']));
                    $obpe->getactivesheet()->setcellvalue('D'.$k, $user_model::getBorrTypeText($v['type_borr']));
                    $obpe->getactivesheet()->setcellvalue('E'.$k, substr($v['identity'],6,4));
                    $obpe->getactivesheet()->setcellvalue('F'.$k, $user_model::getAccountStatusText($v['account_status']));
                    $obpe->getactivesheet()->setcellvalue('G'.$k, $v['mobile']);
                    $obpe->getactivesheet()->setcellvalue('H'.$k, $v['email']);
                    $obpe->getactivesheet()->setcellvalue('I'.$k, $v['qq']);
                    $obpe->getactivesheet()->setcellvalue('J'.$k, "'".$v['identity']);
                    $obpe->getactivesheet()->setcellvalue('k'.$k, empty($v['sesame_score'])?'0':$v['sesame_score']);
                }
            }
            /* 设置宽度 */
            foreach($cell_title_arr AS $ckey=>$cval){
                $obpe->getActiveSheet()->getColumnDimension($cval)->setWidth($width_arr[$ckey]);
            }
        }
        //写入类容
        $obwrite = \PHPExcel_IOFactory::createWriter($obpe, 'Excel5');
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-execl');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header("Content-Disposition:attachment;filename='本站用户列表.xls'");
        header('Content-Transfer-Encoding:binary');
        $obwrite->save('php://output');

    }
    /**
     * 导出本站用户 类型2
     */
    function export_app_user2(){
        $wheres = I('wheres');
        $wheres_str = htmlspecialchars_decode($wheres);
        $where_arr=json_decode($wheres_str,true);
        if(in_array('a.account_status=3',$where_arr)){
            $this->error('无法导出暂时不需要客户!');
        }
        if(in_array('a.account_status=1',$where_arr)){
            $this->error('无法导出已认证客户!');
        }
        $count = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->where( implode( ' and ', $where_arr ) )->count( 'id' );
        if($count>20000){
            $this->error('无法导出超过20000条以上数据!');
        }

        $user_model = new User();
        $mulit_arr = array(
            array("注册时间","姓名","资料审核状态","借款状态","年龄","资料认证状态","手机","微信","QQ","身份证","芝麻分"),
        );
        //列数,需要时再添加,避免多次循环
        $cell_title_arr = ['A','B','C','D','E','F','G','H','I','J','K'];
        $width_arr = [20,10,15,15,30,15,20,15,15,25,15];
        /* @实例化 */
        vendor('PHPExcel.PHPExcel');
        $obpe = new \PHPExcel();

        $step = 5000;
        for ($i=0; $i<$count; $i=$i+$step) {
            $list = M("user a", 'system_', C('DB_CONFIG2'))->where(implode( ' and ', $where_arr ))
                ->field('a.crtime,a.name,a.type,a.type_borr,a.identity,a.account_status,
                    a.mobile,a.email,a.qq,a.sesame_score')
                ->order(['a.modtime' => 'DESC', 'a.crtime' => 'DESC'])
                ->limit($i . ',' . $step)
                ->select();
            if($i!=0){
                $obpe->createSheet();
            }
            $obpe->setactivesheetindex($i);
            //写入多行数据
            array_unshift($list,$mulit_arr);
            foreach($list as $k=>$v){
                $k = $k+1;
                if($k==1){
                    /* @func 设置列-表头 */
                    foreach($cell_title_arr AS $ckey=>$cval){
                        $obpe->getactivesheet()->setcellvalue($cval.$k, $v[0][$ckey]);
                    }
                }else{
                    /* @func 设置列 */
                    $obpe->getactivesheet()->setcellvalue('A'.$k, $v['crtime']);
                    $obpe->getactivesheet()->setcellvalue('B'.$k, $v['name']);
                    $obpe->getactivesheet()->setcellvalue('C'.$k, $user_model::getUserTypeText($v['type']));
                    $obpe->getactivesheet()->setcellvalue('D'.$k, $user_model::getBorrTypeText($v['type_borr']));
                    $obpe->getactivesheet()->setcellvalue('E'.$k, substr($v['identity'],6,4));
                    $obpe->getactivesheet()->setcellvalue('F'.$k, $user_model::getAccountStatusText($v['account_status']));
                    $obpe->getactivesheet()->setcellvalue('G'.$k, $v['mobile']);
                    $obpe->getactivesheet()->setcellvalue('H'.$k, $v['email']);
                    $obpe->getactivesheet()->setcellvalue('I'.$k, $v['qq']);
                    $obpe->getactivesheet()->setcellvalue('J'.$k, "'".$v['identity']);
                    $obpe->getactivesheet()->setcellvalue('k'.$k, empty($v['sesame_score'])?'0':$v['sesame_score']);
                }
            }
            /* 设置宽度 */
            foreach($cell_title_arr AS $ckey=>$cval){
                $obpe->getActiveSheet()->getColumnDimension($cval)->setWidth($width_arr[$ckey]);
            }
        }

        $obpe->setactivesheetindex(0);
        //写入类容
        $obwrite = \PHPExcel_IOFactory::createWriter($obpe, 'Excel5');
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-execl');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header("Content-Disposition:attachment;filename='本站用户列表.xls'");
        header('Content-Transfer-Encoding:binary');
        $obwrite->save('php://output');

    }
    /**
     * 风控审核
     */
    public function risk_audit(){
        $request = I( 'request.' );
        $request['byusers'] = empty( $request['byusers'] ) ? 0 : $request['byusers'];
        $group = get_groups_admin_user();
        switch($request['byusers']) {
            case '2':
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers=' . get_current_admin_id();
                } else {
                    $wheres[] = 'a.byusers!="0"';
                }
                break;
            case '3':
                $group = get_groups_admin_user();
                if($group == 3 || $group == 8) {
                    $wheres[] = 'a.byusers in (' . get_current_admin_id() . ',0)';
                }
                break;
            default:
                $wheres[] = 'a.byusers="0"';
        }
        $is_dis = true;
        $is_di = [];
        $request['is_dis'] = empty( $request['is_dis'] ) ? 0 : $request['is_dis'];
        switch($request['is_dis']) {
            case '2':
                $wheres[] = 'a.is_dis="1"';
                $is_dis = true;
                break;
            case '3':
                break;
            default:
                $wheres[] = 'a.is_dis="0"';
        }
        //资料认证状态
        $account_status = I('account_status',-1);
        $this->account_status = $account_status;
        if($account_status!=-1 && $account_status!='4') {
            $wheres[] = 'a.account_status = '.$account_status;
        }
        if ($account_status=='4'){//除了已认证
            $wheres[] = 'a.account_status != 1';
        }
        if(!empty( $request['name'] )) {
            $wheres[] = 'a.name like "%' . $request['name'] . '%"';
        }
        if(!empty( $request['mobile'] )) {
            $wheres[] = 'a.mobile like "%' . $request['mobile'] . '%"';
        }
        if(!empty( $request['identity'] )) {
            $wheres[] = 'a.identity like "%' . $request['identity'] . '%"';
        }
        if(!empty( $request['starts'] )) {
            $wheres[] = 'a.crtime>="' . date( 'Y-m-d 00:00:00', strtotime( $request['starts'] ) ) . '"';
        }
        if(!empty( $request['ends'] )) {
            $wheres[] = 'a.crtime<="' . date( 'Y-m-d 23:59:59', strtotime( $request['ends'] ) ) . '"';
        }
        $request['type_borr'] = empty( $request['type_borr'] ) ? 0 : $request['type_borr'];
        if($request['type_borr'] != '') {
            $wheres[] = 'a.type_borr="' . $request['type_borr'] . '"';
        }
        $request['type'] = empty( $request['type'] ) ? 0 : $request['type'];
        if($request['type'] != '') {
            $wheres[] = 'a.type="' . $request['type'] . '"';
        }else{
            $wheres[] = '(a.type=5 OR a.type=6)';
        }
        if(!empty( $request['starts_zmf'] )) {
            $wheres[] = 'a.sesame_score>="' . $request['starts_zmf'] . '"';
        }
        if(!empty( $request['ends_zmf'] )) {
            $wheres[] = 'a.sesame_score<="' . $request['ends_zmf'] . '"';
        }
        if(!empty( $request['education'] )) {
            $wheres[] = 'a.education="' . $request['education'] . '"';
        }
        $shenhe = I( 'request.fengkong', 0 );
        if(!empty( $shenhe )) {
            $ur = M( 'users' )->field( 'id' )->where( 'user_login like "%' . $shenhe . '%"' )->select();
            if(empty( $ur )) {
                $wheres[] = 'a.byusers=0';
            } else {
                $i = [];
                foreach($ur as $v) {
                    $i[] = $v['id'];
                }
                if($group == 3 || $group == 8) {

                } else {
                    $wheres[] = 'a.byusers in (' . implode( ',', $i ) . ')';
                }
            }
        }
        $unapproved = I( 'request.unapproved', 0 );
        if(!empty($unapproved) && is_numeric($unapproved)){
            $wheres[] = 'a.unapproved='.$unapproved;
        }
        $count = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->where( implode( ' and ', $wheres ) )->count( 'id' );
        $page = $this->page( $count, 20 );

        $order = empty($order)?['a.modtime' =>'DESC','a.crtime'=>'DESC']:$order;
        $list = M( "user a", 'system_', C( 'DB_CONFIG2' ) )->where( implode( ' and ', $wheres ) )
            ->field( 'a.unapproved,a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,a.code,a.reflux_status,
            a.sesame_score,a.borr_record,a.accept_bind' )
            //->field('a.id,a.crtime,a.name,a.type,a.type_borr,a.identity,a.byusers,a.photo_type,a.education,a.account_status,a.is_dis,c.name as dis_name')
            //->join("LEFT JOIN system_distribution c on c.code=a.code")
            ->order( $order )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        //print_r(M( "user a", 'system_', C( 'DB_CONFIG2' ) )->_sql());exit;
        $ids = [];
        $codes = [];
        foreach($list as $v) {
            if(!empty( $v['byusers'] )) {
                $ids[] = $v['byusers'];
            }
            if(!empty( $is_dis )) {
                $is_di[] = $v['id'];
            }
            if(!empty( $v['code'] )) {
                $codes[] = "'" . $v['code'] . "'";
            }
        }
        if(!empty( $ids )) {
            $buyer = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
            $buyers = [];
            foreach($buyer as $v) {
                $buyers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'buyers', $buyers );
        }
        if(!empty( $is_di )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'is_dis=1 and user_id in (' . implode( ',', $is_di ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['user_id']] = $v['code'];
            }
            $this->assign( 'is_dis', $is_ids );
        }
        if(!empty( $codes )) {
            $is_id = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( 'code in (' . implode( ',', $codes ) . ')' )->select();
            $is_ids = [];
            foreach($is_id as $v) {
                $is_ids[$v['code']] = $v['name'];
            }
            $this->assign( 'codes', $is_ids );
        }
        //获取审核用户
        $shen_user = M( "users" )->alias( "a" )->join( C( 'DB_PREFIX' ) . 'role_user as b on a.id =b.user_id' )->where( 'b.role_id in (3,8) and a.user_status=1' )->order( 'a.id desc' )->select();
        $this->assign( 'unapproved', $this->unapproved );
        $this->assign( 'shen_user', $shen_user );
        $this->assign( 'wheres_str', implode(',',$wheres) );
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display(':risk_audit');
    }

    public function jum_ban()
    {
        $id = I( 'get.id', 0, 'intval' );
        if(!empty( $id )) {
            if($type=I( 'get.type', 0, 'intval' )){
                $result = $this->user_model->where( [ "id" => $id, "type_borr" => 2 ] )->setField( 'type_borr', 1 );
                if($result) {
                    $message_log = [
                        'user_id' => $id,
                        'examine_id' => get_current_admin_id(),
                        'message' => '重新验证运营商',
                        'status' => 1,
                        'types' => 2,
                        'amount' => 0,
                        'stages' => 1,
                        'deposit' => 0,
                    ];
                    M( "log", 'system_', C( 'DB_CONFIG2' ) )->add( $message_log );
                    $this->success( "重新验证运营商成功!", U( "indexadmin/index" ) );
                } else {
                    $this->error( '该客户已经需要重新填写运营商!' );
                }
            }else{
                $result = $this->user_model->where( [ "id" => $id, "type_borr" => 1 ] )->setField( 'type_borr', 2 );
                if($result) {
                    $message_log = [
                        'user_id' => $id,
                        'examine_id' => get_current_admin_id(),
                        'message' => '跳过运营商验证',
                        'status' => 1,
                        'types' => 2,
                        'amount' => 0,
                        'stages' => 1,
                        'deposit' => 0,
                    ];
                    M( "log", 'system_', C( 'DB_CONFIG2' ) )->add( $message_log );
                    $this->success( "跳过运营商成功!", U( "indexadmin/index" ) );
                } else {
                    $this->error( '跳过运营商失败!' );
                }
            }
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    // 后台本站用户禁用
    public function ban()
    {
        $id = I( 'get.id', 0, 'intval' );
        if($id) {
            $result = M( "Users" )->where( [ "id" => $id, "user_type" => 2 ] )->setField( 'user_status', 0 );
            if($result) {
                $this->success( "会员拉黑成功！", U( "indexadmin/index" ) );
            } else {
                $this->error( '会员拉黑失败,会员不存在,或者是管理员！' );
            }
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    // 后台本站用户启用
    public function cancelban()
    {
        $id = I( 'get.id', 0, 'intval' );
        if($id) {
            $result = M( "Users" )->where( [ "id" => $id, "user_type" => 2 ] )->setField( 'user_status', 1 );
            if($result) {
                $this->success( "会员启用成功！", U( "indexadmin/index" ) );
            } else {
                $this->error( '会员启用失败！' );
            }
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     * 编辑用户信息
     */
    public function info()
    {
        $id = I( 'get.id', 0, 'intval' );
        if($id) {
            $result = $this->user_model
                ->join( "LEFT JOIN attachment a on system_user.silver_photo=a.id and system_user.id=a.user_id" )
                ->join( "LEFT JOIN warehouse b on system_user.id=b.user_id" )
                ->where( [ "system_user.id" => $id ] )
                ->field( 'b.credit_lines,a.url,system_user.*' )->find();
            $bank = M( "bank", 'system_', C( 'DB_CONFIG2' ) )->select();
            $education = M( "education", 'system_', C( 'DB_CONFIG2' ) )->select();
            //if(!empty($result['is_dis'])){
            $isdis = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['id'], 'is_dis' => 1 ] )->find();
            $this->assign( 'isdis', $isdis );
            //}
            $this->assign( 'user', $result );
            $this->assign( 'bank', $bank );
            $this->assign( 'education', $education );
            $this->assign( 'type', $result['account_status'] );
            $this->display( ":info" );
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    public function see()
    {
        $id = I( 'get.id', 0, 'intval' );//用户ID
        //来源表头
        $from_type = I('get.from_type');
        switch ($from_type){
            case '1':
                $from_url = U('indexadmin/index');
                $from_text = '本站用户';
                break;
            case '2':
                $from_url = U('indexadmin/risk_audit');
                $from_text = '风控审核';
                break;
            case '3':
                $from_url = U('indexadmin/myuser');
                $from_text = '我的客户';
                break;
            case '4':
                $from_url = U('indexadmin/reflux_user',['byusers'=>3]);
                $from_text = '回流用户';
                break;
            case '5':
                $from_url = U('examine/loan');
                $from_text = '初次已放款列表';
                break;
            default:
                $from_url = U('indexadmin/index');
                $from_text = '本站用户';
                break;
        }
        $this->assign('from_url', $from_url);
        $this->assign('from_text', $from_text);

        if($id) {
            $result = $this->user_model->join( "LEFT JOIN attachment a on system_user.silver_photo=a.id and system_user.id=a.user_id" )
                ->where( [ "system_user.id" => $id ] )
                ->field( 'a.url,system_user.*' )->find();
            $bank = M( "bank", 'system_', C( 'DB_CONFIG2' ) )->select();
            $education = M( "education", 'system_', C( 'DB_CONFIG2' ) )->select();
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'types' => '2', 'user_id' => $id ] )->select();
            if(!empty( $log )) {
                $ids = [];
                foreach($log as $v) {
                    $ids[$v['examine_id']] = $v['examine_id'];
                }
                $u = [];
                $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
                foreach($us as $v) {
                    $u[$v['id']] = $v['user_login'];
                }
                $this->assign( 'users', $u );
            }
            if(!empty( $result['is_dis'] )) {
                $isdis = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['id'], 'is_dis' => 1 ] )->find();
                $this->assign( 'isdis', $isdis );
            }
            $mobile_list = $this->get_user_mobile_list( $result['id'], true );
            //rong360报告的西瓜分
            $decision = M( 'user_report360', 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['id'],'decision_score'=>['neq',''] ] )->getField( 'decision_score' );
            //用户运营审核备注信息
            $userRemarks = (new \User\Model\UserRemarksModel())->where(['user_id'=>$id])->select();
            $this->assign('userRemarks',$userRemarks);
            $this->assign( 'decision', $decision );
            $this->assign( 'mobile_list', $mobile_list['list'] );
            $this->assign( 'page', $mobile_list['page'] );
            $this->assign( 'log', $log );
            $this->assign( 'user', $result );
            $this->assign( 'bank', $bank );
            $this->assign( 'education', $education );
            $this->display( ":see" );
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    public function info_save()
    {
        $data = I( 'post.options' );
        $photo = I( 'post.photos_url' );
        if(!empty( $data['id'] )) {
            if(strpos($data['other_mobile'],'*')){
                unset( $data['other_mobile'] );
            }
            if(empty( $data['password'] )) {
                unset( $data['password'] );
            } else {
                $data['password'] = md5( $data['password'] );
            }
            if(!empty( $photo )) {
                $data['photos_url'] = json_encode( $photo );
            } else {
                $data['photos_url'] = '';
            }
            if(!empty( $data['messgae'] )){
                $add=[
                    'user_id'=>$data['id'],
                    'examine_id'=>get_current_admin_id(),
                    'status'=>1,
                    'types'=>2,
                    'message'=>$data['messgae'],
                ];
                M( 'log', 'system_', C( 'DB_CONFIG2' ) )->add( $add );
                unset($data['messgae']);
            }
            switch (I( 'request.dis' )){
                case '1':
                    $url=U( "indexadmin/unwanted_user" );
                    break;
                case '2':
                    $url=U( "indexadmin/index" );
                    break;
                default:
                    $url='javascript:history.back(-1)';
            }
            $this->user_model->where( [ 'id' => $data['id'] ] )->save( $data );
            if(is_numeric($data['credit_lines'])){
                M( 'house', 'ware', C( 'DB_CONFIG2' ) )
                    ->where( [ 'user_id' =>$data['id']] )->save( ['credit_lines'=>$data['credit_lines']] );
            }
            //$this->success( "会员编辑成功！", U( "indexadmin/index" ) );
            $this->success( "会员编辑成功！",  $url);
        } else {
            $this->error( '请刷新重试！' );
        }
    }

    /*
     * 审核
     */
    public function examine()
    {
        $id = I( 'get.id', 0, 'intval' );
        if(!empty( $id )) {
            $result = $this->user_model->join( "LEFT JOIN attachment a on system_user.silver_photo=a.id and system_user.id=a.user_id" )
                ->where( [ "system_user.id" => $id ] )
                ->field( 'a.url,system_user.*' )->find();
            $bank = M( "bank", 'system_', C( 'DB_CONFIG2' ) )->select();
            $education = M( "education", 'system_', C( 'DB_CONFIG2' ) )->select();
            $this->assign( 'user', $result );
            $this->assign( 'bank', $bank );
            $this->assign( 'education', $education );
            $this->display( ":examine" );
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    public function examine_act()
    {
        $data = I( 'post.options' );
        $type = I( 'get.display', 0 );
        if(!empty( $data['id'] )) {
            if(empty( $type )) {
                $dt = [
                    'type' => 0,
                    'examine' => '审核失败,验证不通过!',
                    'silver_stutas' => 2,
                ];
            } else {
                $dt = [
                    'type' => 3,
                    'silver_stutas' => 1,
                    'examine' => '审核成功',
                ];
            }
            set_log( $data['id'], 2, $type, $dt['examine'] );
            $this->user_model->where( [ 'id' => $data['id'] ] )->save( $dt );
            $this->success( "审核成功！", 'javascript:history.back(-1)' );
        } else {
            $this->error( '请刷新重试！' );
        }
    }

    /*
     * 联系资料审核
     */
    public function contact_exam()
    {
        $id = I( 'get.id', 0, 'intval' );
        if(!empty( $id )) {
            $result = $this->user_model->join( "LEFT JOIN attachment a on system_user.silver_photo=a.id and system_user.id=a.user_id" )
                ->where( [ "system_user.id" => $id ] )
                ->field( 'a.url,system_user.*' )->find();
            $bank = M( "bank", 'system_', C( 'DB_CONFIG2' ) )->select();
            $education = M( "education", 'system_', C( 'DB_CONFIG2' ) )->select();
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'types' => '2', 'user_id' => $id ] )->select();
            if(!empty( $log )) {
                $ids = [];
                foreach($log as $v) {
                    $ids[$v['examine_id']] = $v['examine_id'];
                }
                $u = [];
                $us = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();
                foreach($us as $v) {
                    $u[$v['id']] = $v['user_login'];
                }
                $this->assign( 'users', $u );
            }
            $this->assign( 'log', $log );
            $this->assign( 'user', $result );
            $this->assign( 'bank', $bank );
            $this->assign( 'education', $education );
            $this->display( ":contact" );
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     * 通过 "系统审核不通过"的人
     */
    public function type_exam()
    {
        $id = I( 'get.id', 0, 'intval' );
        if(!empty( $id )) {
            $where['id'] = $id;
            $where['type'] = '8';
            $data['type'] = '5';
            $us = $this->user_model->where( $where )->save( $data );
            if($us) {
                $this->success( '通过成功！' );
            } else {
                $this->error( '通过失败！！！' );
            }
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    public function contact_act()
    {
        $data = I( 'post.options' );
        if(!empty( $data )) {
            $type = $data['display'];
            //if(empty( $type )) {
            //    $msg = !empty( $data['messgae'] ) ? $data['messgae'] : '审核失败';
            //    $data['account_status'] = 2;
            //    $this->user_model->where( [ 'id' => $data['id'] ] )->save( $data );
            //    //拒绝订单
            //    M( "ders", 'or', C( 'DB_CONFIG2' ))->where(['user_id' => $data['id'],'status'=>'0'])->save(['status'=>'6']);
            //    $type=0;
            //} else {
            //    $msg = !empty( $data['messgae'] ) ? $data['messgae'] : '审核成功';
            //    $data['account_status'] = 1;
            //    $this->user_model->where( [ 'id' => $data['id'] ] )->save( $data );//data需要细化
            //    $type=1;
            //}
            switch($type){
                case 0:
                    $status=0;
                    $msg = !empty( $data['messgae'] ) ? $data['messgae'] : '审核失败';
                    $data['account_status'] = 2;
                    $data['unapproved'] = $data['user_status_shen'];
                    unset($data['user_status_shen']);
                    unset($data['user_status_he']);
                    $this->user_model->where( [ 'id' => $data['id'] ] )->save( $data );
                    //拒绝订单
                    M( "ders", 'or', C( 'DB_CONFIG2' ))->where(['user_id' => $data['id'],'status'=>'0'])->save(['status'=>'6']);
                    break;
                case 1:
                    $status=1;
                    $msg = !empty( $data['messgae'] ) ? $data['messgae'] : '审核成功';
                    $data['account_status'] = 1;
                    unset($data['user_status_shen']);
                    unset($data['user_status_he']);
                    $this->user_model->where( [ 'id' => $data['id'] ] )->save( $data );//data需要细化
                    break;
                case 2:
                    $status=0;
                    $msg = !empty( $data['messgae'] ) ? $data['messgae'] : '暂时不需要';
                    $data['account_status'] = 3;
                    $data['reflux_status'] = 0;//回流
                    $data['unapproved'] = $data['user_status_he'];
                    unset($data['user_status_shen']);
                    unset($data['user_status_he']);
                    $this->user_model->where( [ 'id' => $data['id'] ] )->save( $data );
                    //拒绝订单
                    M( "ders", 'or', C( 'DB_CONFIG2' ))->where(['user_id' => $data['id'],'status'=>'0'])->save(['status'=>'6']);
                    break;
                default:
                    $status=0; $msg='';
                    break;
            }
            set_log( $data['id'], 2, $status, $msg );
//            $url = $this->jum_url . "?app_act=index/wechat_r_f";
//            $post_data = [
//                'id' => $data['id'],
//                'amount' => $type ? 1 : 0,
//                'type' => 5,
//                'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $data['id'] ),
//            ];
//            A( 'indexlinks' )->http_post( $url, $post_data );
            $mobile=$this->user_model->field('mobile')->where([ 'id' => $data['id'] ])->find();
            $other=M( "user", 'system_', C( 'DB_CONFIG3' ))->field('id,account_status')->where(['mobile'=>$mobile['mobile']])->find();
            if(!empty($other['id']) && empty($other['account_status'])){
                M( "user", 'system_', C( 'DB_CONFIG3' ))->where(['id'=>$other['id']])->save(['code'=>'zKndy']);
            }
            $this->success( "审核成功！", 'javascript:history.back(-1)' );
        } else {
            $this->error( '数据传入失败！' );
        }
    }

    /*
     * 我的客户
     */
    function myuser()
    {
        $where = [];
        $request = I( 'request.' );
        $where['byusers'] = [ 'eq', get_current_admin_id() ];
        if(!empty( $request['name'] )) {
            $where['name'] = [ 'like', "%{$request['name']}%" ];
        }
        if(!empty( $request['mobile'] )) {
            $where['mobile'] = [ 'like', "%{$request['mobile']}%" ];
        }
        if(!empty( $request['identity'] )) {
            $where['identity'] = [ 'like', "%{$request['identity']}%" ];
        }
        if(!empty( $request['starts'] )) {
            $where['starts'] = [ 'egt', $request['mobile'] ];
        }
        if(!empty( $request['ends'] )) {
            $where['ends'] = [ 'elt', $request['ends'] ];
        }
        if($request['type_borr'] != '') {
            $where['type_borr'] = [ 'eq', $request['type_borr'] ];
        }
        if($request['type'] != '') {
            $where['type'] = [ 'eq', $request['type'] ];
        }
        $count = $this->user_model->where( $where )->count();
        $page = $this->page( $count, 20 );

        $list = $this->user_model
            ->where( $where )
            ->order( [ 'claim_time' => 'DESC', 'crtime' => 'DESC' ] )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        $num=[];
        foreach($list as $v){
            if(!is_numeric($v['mobile'])){
                continue;
            }
            $num[$v['mobile']]=$v['mobile'];
        }
        if(!empty($num)){
            $log=M( "log", 'sms_', C( 'DB_CONFIG2' ))->field('id,mobile')->where('mobile in ('.implode(',',$num).') and type=3')->select();
            $logs=[];
            foreach($log as $v){
                $logs[$v['mobile']]=$v['id'];
            }
            $this->assign( 'send_sms', $logs );
        }
        $this->assign( 'unapproved', $this->unapproved );
        $this->assign( 'list', $list );
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->assign( 'wheres_str', json_encode($where) );
        $this->display( ":myuser" );
    }

    /**
     * 导出我的用户
     */
    function export_myuser(){
        $this->error();
        $wheres = I('wheres');
        $wheres_str = htmlspecialchars_decode($wheres);
        $where_arr = json_decode($wheres_str);
        $count = $this->user_model->where( $where_arr )->count();
        if($count>20000){
            $this->error('无法导出超过20000条以上数据!');
        }

        $user_model = new User();
        $mulit_arr = array(
            array("手机号码","姓名","资料审核状态","借款状态","身份证","注册时间","资料认证状态"),
        );
        /* @实例化 */
        vendor('PHPExcel.PHPExcel');
        $obpe = new \PHPExcel();


        $step = 5000;
        for ($i=0; $i<$count; $i=$i+$step) {
            $list = $this->user_model
                ->field('mobile,name,type,type_borr,substr(identity,7,9) AS identity,crtime,account_status')
                ->where( $where_arr )
                ->order( [ 'claim_time' => 'DESC', 'crtime' => 'DESC' ] )
                ->limit( $i . ',' . $step)
                ->select();
            if($i!=0){
                $obpe->createSheet();
            }
            $obpe->setactivesheetindex($i);
            //写入多行数据
            array_unshift($list,$mulit_arr);
            foreach($list as $k=>$v){
                $k = $k+1;
                if($k==1){
                    /* @func 设置列 */
                    $obpe->getactivesheet()->setcellvalue('A'.$k, $v[0][0]);
                    $obpe->getactivesheet()->setcellvalue('B'.$k, $v[0][1]);
                    $obpe->getactivesheet()->setcellvalue('C'.$k, $v[0][2]);
                    $obpe->getactivesheet()->setcellvalue('D'.$k, $v[0][3]);
                    $obpe->getactivesheet()->setcellvalue('E'.$k, $v[0][4]);
                    $obpe->getactivesheet()->setcellvalue('F'.$k, $v[0][5]);
                    $obpe->getactivesheet()->setcellvalue('F'.$k, $v[0][6]);
                }else{
                    /* @func 设置列 */
                    $obpe->getactivesheet()->setcellvalue('A'.$k, $v['mobile']);
                    $obpe->getactivesheet()->setcellvalue('B'.$k, $v['name']);
                    $obpe->getactivesheet()->setcellvalue('C'.$k, $user_model::getUserTypeText($v['type']));
                    $obpe->getactivesheet()->setcellvalue('D'.$k, $user_model::getBorrTypeText($v['type_borr']));
                    $obpe->getactivesheet()->setcellvalue('E'.$k, $v['identity']);
                    $obpe->getactivesheet()->setcellvalue('A'.$k, $v['crtime']);
                    $obpe->getactivesheet()->setcellvalue('F'.$k, $user_model::getAccountStatusText($v['account_status']));
                }
            }
            /* 设置宽度 */
            $obpe->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $obpe->getActiveSheet()->getColumnDimension('B')->setWidth(10);
            $obpe->getActiveSheet()->getColumnDimension('C')->setWidth(15);
            $obpe->getActiveSheet()->getColumnDimension('D')->setWidth(15);
            $obpe->getActiveSheet()->getColumnDimension('E')->setWidth(30);
            $obpe->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $obpe->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        }

        $obpe->setactivesheetindex(0);
        //写入类容
        $obwrite = \PHPExcel_IOFactory::createWriter($obpe, 'Excel5');
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-execl');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header("Content-Disposition:attachment;filename='我的客户列表.xls'");
        header('Content-Transfer-Encoding:binary');
        $obwrite->save('php://output');
    }

    /*
     * 批量认领
     */
    function bate_add()
    {
        $dt = I( 'post.id', 0 );
        $dis = I( 'request.display', 0 );
        $str = $dis ? 'byusers_loan' : 'byusers';
        $user = $this->user_model->where( 'id in (' . implode( ',', $dt ) . ')' )->where( [ $str => [ 'eq', 0 ] ] )->field( 'id' )->select();
        if(empty( $user )) {
            $this->error( "选择的用户已被认领！" );
        }
        $ids = [];
        foreach($user as $v) {
            $ids[] = $v['id'];
        }
        if($dis) {
            $save = [
                $str => get_current_admin_id(),
            ];
        } else {
            $save = [
                $str => get_current_admin_id(),
                'claim_time' => date( 'Y-m-d H:i:s' ),
            ];
        }
        $this->user_model->where( 'id in (' . implode( ',', $ids ) . ')' )->save( $save );
        $this->success( "添加成功！" );
    }

    /*
     * 记录
     */
    function log_users($user_id = '', $type = '1')
    {
        if(empty( $user_id )) {
            return;
        }
        $where = [
            'user_id' => $user_id,
        ];
        $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( $where )->where( 'types in (' . $type . ')' )->select();
        return $log;
    }

    /*
     * 分销用户添加
     */
    function add()
    {
        $data = I( 'post.options' );
        if(!empty( $data['name'] ) && !empty( $data['code'] )) {
            $user = $this->user_model->field( 'id,name,is_dis' )->where( [ 'identity' => $data['name'] ] )->find();
            if(empty( $user['id'] )) {
                $this->error( '用户不存在！', $data['url'] );
            }
            $d = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $user['id'], 'is_dis' => 1 ] )->field( 'code' )->find();
            if(!empty( $d['code'] )) {
                $this->error( '该用户已生成了推荐码,请勿重复操作！', $data['url'] );
            }
            $dt = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'code' => $data['code'], 'is_dis' => 1 ] )->field( 'code' )->find();
            if(!empty( $dt )) {
                $this->error( '该推荐码已存在,请重新选择！', $data['url'] );
            }
            if($user['is_dis'] == 0) {
                $update = [
                    'is_dis' => '1',
                ];
                $this->user_model->where( [ 'identity' => $data['name'] ] )->save( $update );
            }
            $insert = [
                'name' => $user['name'],
                'code' => $data['code'],
                'user_id' => $user['id'],
                'is_dis' => 1,
            ];
            M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->add( $insert );
            $this->success( "添加成功！", 'javascript:history.back(-1);' );
        } else {
            $url = $_SERVER['HTTP_REFERER'];
            if(strstr( $url, 'add' )) {
                $url = session( 'indexadmin_return' );
            } else {
                session( 'indexadmin_return', $url );
            }
            $this->assign( 'url', $url );
            $this->display( ":add" );
        }
    }

    function get_user_mobile_list($id = '', $type = false)
    {
        if(empty( $id ) || !is_numeric( $id )) {
            $this->error( '数据传入失败！' );
        }
        $count = M( "mobile_list", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $id ] )->count();
        $page = $this->page( $count, 10 );
        $list = M( "mobile_list", 'system_', C( 'DB_CONFIG2' ) )
            ->where( [ 'user_id' => $id ] )
            ->order( "crtime DESC,mobile desc" )
            ->limit( $page->firstRow . ',' . $page->listRows )
            ->select();
        $data = [
            'Total_Pages' => $page->Total_Pages,
            'list' => $list,
            'Current_page' => $page->Current_page,
            'count' => $count,
            'page' => $page->show( 'Admin' ),
        ];
        if($type) {
            return $data;
        }
        $this->ajaxReturn( $data );
    }

    function mobile_down()
    {
        $id = I( 'request.id' );
        $url = "http://www.nuonuojinfu.cn/?app_act=index/daochu&";
        $post_data = [
            'sign=' . md5( '导出' . md5( 'nuonuojinfu321' ) . $id ),
            'user_id=' . $id,
            //'user_id=4519',
        ];
        redirect( $url . implode( '&', $post_data ) );
        //A('indexlinks')->http_get();
        exit;
    }

    /*
     * 转让
     */
    function transfer()
    {
        $data = I( 'post.' );
        if(empty( $data['us_id'] ) || empty( $data['users'] )) {
            $this->error( '数据传入失败！' );
        }
        $user = explode( ',', $data['users'] );
        foreach($user as $k => $v) {
            if(!is_numeric( $v ) || empty( $v )) {
                unset( $user[$k] );
            }
        }
        if(empty( $user )) {
            $this->error( '数据传入失败！' );
        }
        $lastuser = get_current_admin_id();
        $user_list = M( "user", 'system_', C( 'DB_CONFIG2' ) )->field( 'id,byusers' )->where( 'id in (' . implode( ',', $user ) . ')' )->select();
        $ins = [];
        foreach($user_list as $v) {
            $ins[] = [
                'user_id' => $v['id'],
                'bfuser_id' => empty( $v['byusers'] ) ? 0 : $v['byusers'],
                'auser_id' => $data['us_id'],
                'lastuser_id' => $lastuser,
            ];
            $up = [
                'byusers' => $data['us_id'],
            ];
            M( "user", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'id' => $v['id'] ] )->save( $up );
        }
        M( "trf_log", 'system_', C( 'DB_CONFIG2' ) )->addAll( $ins );
        $this->success( "转让成功！", U( "indexadmin/index" ) );
    }

    /**
     * @use          [管理员层级关系列表]
     * @author       chenxiaogang
     */
    public function admin_level_manager_list()
    {
        $model = new AdminLevel();
        $result = $model->getTreeAll();
        $this->assign("categorys", $result);
        $this->display();
    }

    public function edit_admin_level(){
        $model = new AdminLevel();
        $result = $model->field('admin_id as id,admin_id,pid,level')->select();
        if(IS_GET){
            $tree = new \Tree();
            $id = I("get.id",0,'int');
            $rs = $model->field('admin_id as id,admin_id,pid')->where(array("admin_id" => $id))->find();
            //将所有管理员查出来
            $admins = M('users')->where(['user_status'=>1])->getField('id,user_login');
            //将所有的子ID找出，不能挂在自己的子级ID中
            $sonIds = $model->getAllSonIds($result,$id);//排除所有子级
            $cannotIds = array_merge([$id],$sonIds);//排除自己
            foreach ($result as $k => $r) {
                $prefix = '└─';
                $r['name'] = str_repeat('&nbsp;&nbsp;&nbsp;',$r['level']) . $prefix .$admins[$r['id']];
                $r['selected'] = $r['id'] == $rs['pid'] ? 'selected' : '';
                !in_array($r['id'],$cannotIds) && ($array[] = $r);
            }
            $rs['name'] = $admins[$rs['id']];
            $rs['pname'] = $admins[$rs['pid']];
            $str = "<option value='\$id' \$selected>\$name</option>";
            $tree->init($array);
            $select_categorys = $tree->get_tree(0, $str);
            $this->assign("data", $rs);
            $this->assign("select_categorys", $select_categorys);
            $this->display();
        }elseif(IS_POST){
            $data = I('post.');
            //找出父级ID的等级，然后+1；
            $parent = $model->where(['admin_id'=>$data['pid']])->field('level,path')->find();
            //如果设置的为顶级
            if(empty($parent)){
                $parent = [
                    'path'=>'0',
                    'level'=>0,
                ];
            }
            $model->where(['admin_id'=>$data['id']])->save(['pid'=>$data['pid'],'level'=>$parent['level']+1,'path'=>$parent['path'].'-'.$data['id']]);
            //除了自身，查询自己下面是否有自己，如果有子级，那么子级所有的path和level都要改变
            $sonIds = $model->getAllSonIds($result,$data['id']);
            $parent['path'] = $parent['path']?$parent['path']:'0';
            if(!empty($sonIds)){
                //先改path
                $sql = 'UPDATE cmf_admin_level SET path=CONCAT("'.$parent['path'].'",REPLACE(path,SUBSTRING_INDEX(path,"-'.$data['id'].'-",1),"")) WHERE admin_id IN ('.implode(',',$sonIds).')';
                $model->execute($sql);
                //后根据Path改level
                $sql = 'UPDATE cmf_admin_level SET `level`=LENGTH(path)-LENGTH(REPLACE(path,"-","")) WHERE admin_id IN('.implode(',',$sonIds).')';
                $model->execute($sql);
            }
            $this->success( "调整成功！", U( "indexadmin/admin_level_manager_list" ) );
        }
    }

    public function add_admin(){
        $model = new AdminLevel();
        if(IS_GET){
            $pid = I('get.id',0,'int');
            //获取管理员列表（暂时都获取贷后）
            $userModel = new User();
            $rs = $model->field('admin_id as id,admin_id,pid')->where(array("admin_id" => $pid))->find();
            //排除所有已经存在等级关系列表中的管理员
            $notin = $model->getField('admin_id',true);
            $daihouList = (new \User\Model\RoleUser())->getDaiHouList();//得到贷后人员列表
            $shouldIds = array_unique(array_column($daihouList,'id'));//可以拿到的用户ID列表
            $where = [
                'user_status'=>1,
                'id' => ['in',$shouldIds],
            ];
            if(!empty($notin)){
                $where['id '] = ['not in',$notin];
            }
            $admins = $userModel->where($where)->field('id,user_login')->select();
            $rs['name'] = M('users')->where(['id'=>$pid])->getField('user_login');
            $this->assign('data',$rs);
            $this->assign('admins',$admins);
            $this->assign('id',$pid);
            $this->display();
        }elseif(IS_POST){
            $son_id = I('post.son_id',0,'int');
            $pid = I('post.pid',0,'int');
            //找出父级ID的等级，然后+1；
            $parent = $model->where(['admin_id'=>$pid])->field('level,path')->find();
            //如果设置的为顶级
            if(empty($parent)){
                $parent = [
                    'path'=>'0',
                    'level'=>0,
                ];
            }
            //因为增加了pid的关系，所以要将原来的sonid删除
            $model->where('admin_id='.$son_id)->delete();
            $model->add([
                'admin_id'=>$son_id,
                'pid'=>$pid,
                'level'=>$parent['level']+1,
                'path'=>$parent['path'].'-'.$son_id,
            ]);
            $this->success('设置成功！',U( "indexadmin/admin_level_manager_list" ));
        }
    }

    /**
     * 黑白名单列表
     */
    function blackwhite_list(){
        $mobile = trim(I('mobile',0));
        if(!empty($mobile)){
            $where['u.mobile'] = ['LIKE','%'.$mobile.'%'];
        }
        $name = trim(I('name',0));
        if(!empty($name)){
            $where['u.name'] = ['LIKE','%'.$name.'%'];
        }
        $where['bw.user_type'] = $user_type = I('user_type', 0); //0黑名单  1白名单
        $this->user_type = $user_type;
        //获取黑白名单数量
        $count = M('blackwhite_user','system_',C('DB_CONFIG2'))
            ->alias('bw')->join('system_user u ON u.id = bw.user_id')
            ->where($where)->count();
        $page = $this->page( $count, 10 );
        //获取黑白名单列表
        $this->list = M('blackwhite_user','system_',C('DB_CONFIG2'))
            ->field('bw.id,u.name,u.mobile,bw.add_reason,bw.bw_type,bw.bw_end_time,bw.create_time,bw.createby')
            ->join('system_user u ON u.id = bw.user_id')
            ->alias('bw')->where($where)->order('bw.create_time DESC')->limit($page->firstRow . ',' . $page->listRows )->select();
        //获取操作管理员列表
        $admin_arr = M('blackwhite_user','system_',C('DB_CONFIG2'))->getField('createby',true);
        if(!empty( $admin_arr )) {
            $lastuser = M( 'users' )->where( 'id in (' . implode( ',', $admin_arr ) . ')' )->field( 'id,user_login' )->select();
            $lastusers = [];
            foreach($lastuser as $v) {
                $lastusers[$v['id']] = $v['user_login'];
            }
            $this->assign( 'lastuser', $lastusers );
        }
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display(":blackwhite_list");
    }

    /**
     * 逾期添加黑名单
     */
    function yqAddBlack(){
        $id = I( 'get.id', 0 );//订单表主键ID
        $data = I( 'post.options', 0 );
        $data['user_type'] = I('user_type', 0);
        $this->addBlackWhite(':yqAddBlack',U("Examine/loan_overdue"),$id,$data);
    }

    /**
     * 到期添加黑名单
     */
    function dqAddBlackWhite(){
        $user_type = I('user_type',0);
        $this->user_type = $user_type;
        $this->user_type_str = $user_type==0?'黑':'白';
        $id = I( 'get.id', 0 );//订单表主键ID
        $data = I( 'post.options', 0 );
        $data['user_type'] = $user_type;
        $this->addBlackWhite(':dqAddBlackWhite',U("Examine/loan_expire"),$id,$data);
    }

    /**
     * 根据订单Id添加黑白名单
     * @param $display_page
     * @param $success_url
     * @param $order_id
     * @param $data
     */
    function addBlackWhite($display_page,$success_url,$order_id,$data){
        $request_method = $_SERVER['REQUEST_METHOD'];
        if('GET'==$request_method){
            $this->reparement($order_id);
            $this->display($display_page);
        }else {
            $user_type = $data['user_type'];
            $bw_data['user_id'] = $data['user_id'];
            $bw_data['user_type'] = $user_type;
            $bw_data['add_reason'] = $data['add_reason'];
            $bw_data['bw_type'] = $bw_type = $data['bw_type'];
            $bw_data['bw_end_time'] = $bw_type==0?strtotime($data['bw_end_time']):0;
            $bw_data['create_time'] = time();
            $bw_data['createby'] = get_current_admin_id();//登录管理员ID

            $user_type_str = $user_type == 0?'黑':'白';
            //判断用户是否在黑白名单中
            $b_where = "user_id=".$data['user_id']." AND user_type=".$user_type;
            $b_record = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($b_where)->find();
            //未找到黑白名单记录
            if(empty($b_record)){
                $res = M('blackwhite_user','system_',C('DB_CONFIG2'))->add($bw_data);
                if($res){
                    $this->success( "添加".$user_type_str."名单成功!", $success_url );
                }else{
                    $this->error("添加".$user_type_str."名单失败");
                }
            }else{//黑白名单限制已过期记录
                if($b_record['bw_type']==0&&$b_record['bw_end_time']<time()){
                    //修改黑白名单记录到期时间
                    $update_where['id'] = $b_record['id'];
                    $updata_data['add_reason'] = $data['add_reason'];
                    $updata_data['bw_type'] = $bw_type = $data['bw_type'];
                    $updata_data['bw_end_time'] = $bw_type==0?strtotime($data['bw_end_time']):0;
                    $updata_data['create_time'] = time();
                    $updata_data['createby'] = get_current_admin_id();//登录管理员ID
                    $update_res = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($update_where)->save($updata_data);
                    if($update_res){
                        $this->success( "添加".$user_type_str."名单成功!", $success_url);
                    }else{
                        $this->error("添加".$user_type_str."名单失败");
                    }
                }else{
                    $this->error("该用户已经在".$user_type_str."名单中");
                }
            }
        }
    }

    /*
     * 借款 详情
     * ① 已到期还款表单页面
     * ② 未到期提前还款表单页面
     * ③ 逾期还款
     * ...
     */
    public function reparement($id){
        if($id) {
            //$this->model模型为order表模型
            $result = M( "ders a", 'or', C( 'DB_CONFIG2' ) )
                ->join( "LEFT JOIN system_user b on a.user_id=b.id" )
                ->where( [ "a.id" => $id ] )
                ->field( 'b.bank,b.silver_card,b.silver_number,b.account_status,b.name,b.mobile,b.photos_url,a.*' )->find();//将原订单查出来

            //判断用户是否在黑名单中
            $b_where = "user_id=".$result['user_id']." AND user_type=0 AND (bw_type=1 OR (bw_type=0 AND bw_end_time>".time()."))";
            $b_record = M('blackwhite_user','system_',C('DB_CONFIG2'))->where($b_where)->find();
            if(!empty($b_record)){
                $this->error('该用户已经在黑名单中');
            }

            //获取催收记录
            $order_id = I('id',0);
            $cs_where['order_id'] = $order_id;
            $this->cs_list = M('after_collection','system_',C('DB_CONFIG2'))->where($cs_where)->select();

            $where = [
                'pid' => $id,
                'user_id' => $result['user_id'],
            ];
            $sub = M( "sub", 'orders_', C( 'DB_CONFIG2' ) )->where( $where )->order( "id asc" )->select();//将订单分期查出来，对应order_sub表
            $renewal = M( "renewal", 'orders_', C( 'DB_CONFIG2' ) )
                ->where( [ 'order_id' => $result['order_id'], 'oid' => $result['id'], 'user_id' => $result['user_id'] ] )
                ->order( "crtime desc,id desc" )->select();//将该订单的续期记录查出来
            $ids = [];
            //types解释：
            //0用户审核1订单审核2用户信息审核3续期审核4逾期多出还款记录5逾期还款记录6订单初审7用户申请还款8运营商填写记录9推广记录
            $resul = M( "log", 'system_', C( 'DB_CONFIG2' ) )
                ->where( [ "user_id" => $result['id'] ] )
                //->where( 'types in (1,4,5,6,7)' )
                ->where( 'types in (1,3,4,5,6,7)' )
                ->order( 'crtime desc,id desc' )
                ->select();//用户资金明细记录表，查询该用户的
            foreach($resul as $v) {
                //如何$v为空或者审核人为0（未审核），则跳过
                if(empty( $v ) || $v['examine_id'] == 0) {
                    continue;
                }
                $ids[$v['examine_id']] = $v['examine_id'];//将审核人装进来
                $ids[$v['payee']] = $v['payee'];//将收款人装起来
            }
            $log = M( "log", 'system_', C( 'DB_CONFIG2' ) )->where( [ 'types' => '2', 'user_id' => $result['user_id'] ] )->select();//将用户信息审核记录查出来
            //处理用户信息审核记录
            foreach($log as $v) {
                $ids[$v['examine_id']] = $v['examine_id']; //将用户信息审核审核人装起来
                $ids[$v['payee']] = $v['payee'];//将收款人装起来
            }
            //处理续期记录
            foreach($renewal as $v) {
                if(empty( $v['lastuser_id'] )) {
                    continue;
                }
                $ids[$v['lastuser_id']] = $v['lastuser_id'];//将续期审核人装起来
            }
            if(!empty( $ids )) {
                $lastuser = M( 'users' )->where( 'id in (' . implode( ',', $ids ) . ')' )->field( 'id,user_login' )->select();//将审核人的后台用户ID和用户名查出
                $lastusers = [];
                foreach($lastuser as $v) {
                    $lastusers[$v['id']] = $v['user_login'];
                }
                $this->assign( 'lastuser', $lastusers );
            }
            //result是上面查询的order表的一条记录
            $yue = M( "house", 'ware', C( 'DB_CONFIG2' ) )->where( [ 'user_id' => $result['user_id'] ] )->find();//查询该订单下的该用户的余额

            $result['deposit'] = $yue['deposit'];
            $this->assign( 'log', $log );//将用户信息审核记录查出来
            $this->assign( 'logs', $resul );//用户资金明细记录表，查询该用户的
            $this->assign( 'renewal', $renewal );//用户续期记录
            $this->assign( 'order', $result );//订单记录及用户资金情况
            $this->assign( 'sub', $sub );//订单分期记录
        }
    }

    /**
     * 解除黑白名单
     */
    public function jcBlackWhite(){
        $id = I('id', 0);
        if(empty($id)){
            $this->ajaxReturn(['msg'=>'错误的数据','errorCode'=>1]);
        }
        $where['id'] = $id;
        $res = M('blackwhite_user','system_',C('DB_CONFIG2'))
            ->where($where)->delete();
        if($res){
            $this->ajaxReturn(['msg'=>'解除成功','errorCode'=>0]);
        }else{
            $this->ajaxReturn(['msg'=>'解除失败,请重试','errorCode'=>1]);
        }
    }
    /*
     * 黑名单查询api
     */
    public function black_list_api(){
        $id = I('get.user_id', 0);
        $type = I('get.type', 0);
        $type = $type?1:0;
        if(empty($id)){
            $this->error( '参数有误请刷新重试!' );
        }
        $url = $this->jum_url . "?app_act=index/check_black_list";
        $times='2'.time().'1';
        $post_data = [
            'id' => $id,
            't' => $times,
            'type' => $type,
            'sign' => md5( 'report报告99549f22279e68b6d4036ccf8bdd5f55' . $id .$times),
            'ids'=>I('get.id', 0)
        ];
        $res=A( 'indexlinks' )->http_post( $url, $post_data );
        if(!empty($res) && $res['fh']==4){
            $this->success( $res['msg']);
        }else{
            $this->error( '查询失败!' );
        }
    }

    //除已认证列表
    public function except_authen_user(){
        //资料认证状态
        $reflux_status = I('request.reflux_status');
        /**
         * $reflux_status：0回流状态 1正常 2审核成功
         */
        switch ($reflux_status){
            case '1':
                $where[] = 'reflux_status = 1';
                break;
            case '2':
                $where[] = 'reflux_status = 0';
                break;
            default:
                $where[] = '(reflux_status = 1 OR reflux_status = 0)';
        }
        $where['account_status_str'] = 'a.account_status <> 1';
        $this->show_user($where);
        $this->display();
    }
    /*
     * 初审
     */
    function first_examine(){
        header("Content-type: text/html; charset=utf-8");
        $user_id=I('request.user_id',0);
        if(empty($user_id) || !is_numeric($user_id)){
            $this->error('请选择正确的客户!');
        }
        //$user=M( "user", 'system_', C( 'DB_CONFIG2' ) )->field('mobile')->where(['id'=>$user_id])->find();
        //$user['mobile']='15517630213';
//        $user=M( "user", 'system_', C( 'DB_CONFIG2' ) )->field('mobile')->where(['id'=>$user_id])->find();
//        $log=M( "log", 'sms_', C( 'DB_CONFIG2' ) )->where(['mobile'=>$user['mobile'],'type'=>3])->field(['id'])->find();
//        //print_r($log);exit;
//        if(!empty($log)){
//            $this->error('该初审短信已发送!');
//        }
        //M( "log", 'sms_', C( 'DB_CONFIG2' ))->add($data);
        $sms = new SmsLogModel();
        $type=I('request.type',0);
        if($type){//审核通过
            $content='2867';
            $content='恭喜您在悦花花初审通过,请留意终审人员添加您的QQ进行审核或者通过电话回访您本人';
        }else{
            $content='3576';
            $content='亲爱的客户：非常抱歉，您在悦花花的综合评分不足，暂时不能办理，如需继续办理，请登录APP联系客服';
        }
        $dt=$sms->sms_cry($user_id,$content);
        $this->success('初审短信发送成功');
    }
    /*
     * 其他认证信息
     */
    function add_other_date(){
        $id = I('get.user_id', 0);
        $type = I('get.type', 0);
        switch ($type){
            case '1':
                $type='alipay';
                break;
            default:
                $this->error( '请选择正确的认证!' );
        }
        if(empty($id)){
            $this->error( '参数有误请刷新重试!' );
        }
        $url = $this->jum_url . "?app_act=index/api_report_rong360_data";
        $times='2'.time().'1';
        $post_data = [
            'id' => $id,
            't' => $times,
            'type' => $type,
            'sign' => md5( 'report报告99549f22279e68b6d4036ccf8bdd5f55' . $id .$times),
        ];
        $res=A( 'indexlinks' )->http_post( $url, $post_data );
        print_r($res);exit;
        if(!empty($res) && $res['fh']==4){
            $this->success( $res['msg']);
        }else{
            $this->error( '查询失败!' );
        }
    }
    function yys_raw(){
        $report_id = I('get.id', 0);
        $data=M( "report360_raw", 'system_', C( 'DB_CONFIG2' ))->field('id,report_id')->where(['report_id'=>$report_id])->find();
        if(empty($data)){
            $list=M( "user_report360", 'system_', C( 'DB_CONFIG2' ))->field('id,user_id,search_id')->where(['id'=>$report_id])->find();
            if(empty($list['search_id'])){
                $this->error( '该报告还未生成!' );
            }
            $url = $this->jum_url . "?app_act=index/report_r_f_yys";
            $times='2'.time().'1';
            $post_data = [
                'id' => $list['user_id'],
                'ids' => $list['search_id'],
                'idss' => $list['id'],
                't' => $times,
                'sign' => md5( 'report报告99549f22279e68b6d4036ccf8bdd5f55' . $list['user_id'] .$times),
            ];
            $res=A( 'indexlinks' )->http_post( $url, $post_data );
            if($res['fh']=='4'){
                $this->error($res['msg']);
            }else{
                $this->error( '查询失败,请稍后重试!' );
            }
        }else{
            $list=M( "report360_raw", 'system_', C( 'DB_CONFIG2' ))->field('teldata,msgdata,user_id,report_id,userdata')->where(['id'=>$data['id']])->find();
            $user=M( "user", 'system_', C( 'DB_CONFIG2' ))->field('id,name')->where(['id'=>$list['user_id']])->find();
            $list['teldata']=json_decode($list['teldata'],true);
            $list['msgdata']=json_decode($list['msgdata'],true);
            $list['userdata']=json_decode($list['userdata'],true);
            $mobileList = M('mobile_list','system_',C('DB_CONFIG2'))->where(['user_id'=>$list['user_id']])->getField('mobile,name',true);
            foreach($mobileList as $k=>$v){
                unset($mobileList[$k]);
                $k = str_replace('+86','',trim($k));
                $k = str_replace('-','',trim($k));
                $k = str_replace(' ','',trim($k));
                if(!is_numeric($k)){
                    preg_match_all('/(-?[0-9]\d*)/ism',$k,$number);
                    $k=implode('',$number[1]);
                }
                $mobileList[$k] = $v;
            }
            $this->assign( "mobileList", $mobileList );
            $this->assign( "user", $user );
            $this->assign( "list", $list );
            $this->display(':yys_raw');
        }
    }
    /*
     * 原始数据 通讯
     */
     function yys_raw_down(){
        set_time_limit(120) ;
        ini_set( 'memory_limit', '2048M' );
        //列数,需要时再添加,避免多次循环
        $cell_title_arr = [
            '0'=>['A','B','C','D','E','F','G'],
            '1'=>['A','B','C','D','E','F','G','H','I'],
            '2'=>['A','B','C','D','E','F','G','H'],
        ];
         $report_id = I('get.id', 0);
         $type = I('get.type', 0);
         $mulit_arr = [
             '0' =>['业务类型','费用','对方号码','发送时间','短信地址','信息类型','短信状态'],
             '1' =>['业务类型','通话时间','呼叫类型','费用','套餐优惠','本机通话地','通话时长(秒)','通信类型','对方号码'],
             '2' =>['号码','互联网标识','需求类型','归属地','联系次数','联系时间(分)','主叫次数','被叫次数'],
         ];
         if($type<2){
             $data=M( "report360_raw", 'system_', C( 'DB_CONFIG2' ))->field('id,report_id')->where(['report_id'=>$report_id])->find();
             if(empty($data)){
                 $this->error( '该报告不存在,请稍后重试!' );
             }
             $string=$type?'teldata':'msgdata';//1是通话
             $list=M( "report360_raw", 'system_', C( 'DB_CONFIG2' ))->field($string.',user_id')->where(['id'=>$data['id']])->find();
             $list[$string]=json_decode($list[$string],true);
             $dt=$list[$string];
         }else{
             $string='contact_list';
             $list = M( "report", 'system_user_', C( 'DB_CONFIG2' ) )
                 ->field( 'user_id,'.$string )
                 ->where( [ 'id' => $report_id ] )->find();
             $list[$string]=A( 'Report' )->_arr_sort( $list[$string], 'call_cnt' );
             $list[$string]=json_decode($list[$string],true);
             $dt=[$list[$string]];
         }
         $user=M( "user", 'system_', C( 'DB_CONFIG2' ))->field('id,name')->where(['id'=>$list['user_id']])->find();
         $mobileList = M('mobile_list','system_',C('DB_CONFIG2'))->where(['user_id'=>$list['user_id']])->getField('mobile,name',true);
         foreach($mobileList as $k=>$v){
             unset($mobileList[$k]);
             $k = str_replace('+86','',trim($k));
             $k = str_replace(' ','',str_replace('-','',trim($k)));
             if(!is_numeric($k)){
                 preg_match_all('/(-?[0-9]\d*)/ism',$k,$number);
                 $k=implode('',$number[1]);
             }
             $mobileList[$k] = $v;
         }
         vendor('PHPExcel.PHPExcel');
         $obpe = new \PHPExcel();
         $j=0;
         foreach($dt as $v){
            $obpe->setActiveSheetIndex($j);
             if($type<2){
                 $v['total_size']=empty($v['total_size'])?0:$v['total_size'];
                 $obpe->getActiveSheet()->setTitle($v['month'].'('.$v['total_size'].'条)');
             }else{
                 $obpe->getActiveSheet()->setTitle($user['name'].' 通话数据分析');
                 $items=$v;
                 unset($v);
                 $v['items']=$items;
             }
            $obpe->setactivesheetindex($j);
            $j++;
            //写入多行数据
            array_unshift($v['items'],$mulit_arr[$type]);
             $i=0;
            foreach($v['items'] as $k=>$vs){
                $k+=1;
                if($k==1){
                    /* @func 设置列-表头 */
                    foreach($cell_title_arr[$type] AS $ckey=>$cval){
                        $obpe->getactivesheet()->setcellvalue($cval.$k, $vs[$ckey]);
                    }
                }else{
                    if(empty($vs)){
                        continue;
                    }
                    /* @func 设置列 */
                    switch ($type) {
                        case '0':
                            $obpe->getactivesheet()->setcellvalue('A'.$k, $vs['business_name']);
                            $obpe->getactivesheet()->setcellvalue('B'.$k, $vs['fee']);
                            if(!empty($mobileList[$vs['receiver_phone']])){
                                $vs['receiver_phone'].='('.$mobileList[$vs['receiver_phone']].')';
                            }else{
                                $vs['receiver_phone']="'".$vs['receiver_phone'];
                            }
                            $obpe->getactivesheet()->setcellvalue('C'.$k, "'".$vs['receiver_phone']);
                            $obpe->getactivesheet()->setcellvalue('D'.$k, $vs['send_time']);
                            $obpe->getactivesheet()->setcellvalue('E'.$k, $vs['trade_addr']);
                            if($vs['trade_type']==1){
                                $vs['trade_type']='短信';
                            }elseif($vs['trade_type']==2){
                                $vs['trade_type']='彩信';
                            }else{
                                $vs['trade_type']='其他';
                            }
                            $obpe->getactivesheet()->setcellvalue('F'.$k, $vs['trade_type']);
                            if($vs['trade_way']==1){
                                $vs['trade_way']='发送';
                            }elseif($vs['trade_way']==2){
                                $vs['trade_way']='接收';
                            }else{
                                $vs['trade_way']='未识别状态';
                            }
                            $obpe->getactivesheet()->setcellvalue('G'.$k, $vs['trade_way']);
                            break;
                        case '1':
                            $obpe->getactivesheet()->setcellvalue('A'.$k, $vs['business_name']);
                            $obpe->getactivesheet()->setcellvalue('B'.$k, $vs['call_time']);
                            if($vs['call_type']==1){
                                $vs['call_type']='主叫';
                            }elseif($vs['call_type']==2){
                                $vs['call_type']='被叫';
                            }else{
                                $vs['call_type']='未识别状态';
                            }
                            $obpe->getactivesheet()->setcellvalue('C'.$k, $vs['call_type']);
                            $obpe->getactivesheet()->setcellvalue('D'.$k, $vs['fee']);
                            $obpe->getactivesheet()->setcellvalue('E'.$k, $vs['special_offer']);
                            $obpe->getactivesheet()->setcellvalue('F'.$k, $vs['trade_addr']);
                            $obpe->getactivesheet()->setcellvalue('G'.$k, $vs['trade_time']);
                            if($vs['trade_type']==1){
                                $vs['trade_type']='本地';
                            }elseif($vs['trade_type']==2){
                                $vs['trade_type']='漫游国内';
                            }else{
                                $vs['trade_type']='其他';
                            }
                            $obpe->getactivesheet()->setcellvalue('H'.$k, $vs['trade_type']);
                            if(!empty($mobileList[$vs['receive_phone']])){
                                $vs['receive_phone'].='('.$mobileList[$vs['receive_phone']].')';
                            }else{
                                $vs['receive_phone']="'".$vs['receive_phone'];
                            }
                            $obpe->getactivesheet()->setcellvalue('I'.$k, $vs['receive_phone']);
                            break;
                        case '2':
                            if(!empty($mobileList[$vs['phone_num']])){
                                $vs['phone_num'].='('.$mobileList[$vs['phone_num']].')';
                            }else{
                                $vs['phone_num']="'".$vs['phone_num'];
                            }
                            $obpe->getactivesheet()->setcellvalue('A'.$k, $vs['phone_num']);
                            $obpe->getactivesheet()->setcellvalue('B'.$k, $vs['contact_name']);
                            $obpe->getactivesheet()->setcellvalue('C'.$k, $vs['needs_type']);
                            $obpe->getactivesheet()->setcellvalue('D'.$k, $vs['phone_num_loc']);
                            $obpe->getactivesheet()->setcellvalue('E'.$k, $vs['call_cnt']);
                            $obpe->getactivesheet()->setcellvalue('F'.$k, round($vs['call_len'],2));
                            $obpe->getactivesheet()->setcellvalue('G'.$k, $vs['call_out_cnt']);
                            $obpe->getactivesheet()->setcellvalue('H'.$k, $vs['call_in_cnt']);
                            break;
                    }
                }
                $i++;
                if($i>=18000){
                    break;
                }
            }
            /* 设置宽度 */
            foreach($cell_title_arr[$type] AS $ckey=>$cval){
                $obpe->getActiveSheet()->getColumnDimension($cval)->setWidth(20);
            }
            $obpe->createSheet();
        }
        //写入类容
        $obwrite = \PHPExcel_IOFactory::createWriter($obpe, 'Excel5');
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-execl');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header("Content-Disposition:attachment;filename='".$user['name'].($type?'通讯详单':'短信详单').".xls'");
        header('Content-Transfer-Encoding:binary');
        $obwrite->save('php://output');
     }
    function unlock(){
        $where=[];
        //手机号码
        if($mobile = I( 'request.mobile', 0 )) {
            $where[] = 'u.mobile like "%' . $mobile . '%"';
        }
        //姓名
        if($name = I( 'request.name', 0 )) {
            $where[] = 'u.name like "%' . $name . '%"';
        }
        //是否成人
        $is_adult = I('request.is_adult', -1);
        if('-1'!=$is_adult){
            $where[] = 'u.is_adult =' .$is_adult. '';
        }
        //放款人（财务）
        if($loan_user = I('request.loan_user')){
            $where[] = 'o.loan_user LIKE "%'.$loan_user.'%"';
        }
        //创建日期 - 开始
        if($crtime_start = I('request.crtime_start')){
            $where[] = 'o.loan_time >= "'.$crtime_start.'"';
        }
        //创建日期 - 结束
        if($crtime_end = I('request.crtime_end')){
            $where[] = 'o.loan_time <= "'.$crtime_end.'"';
        }
        $count = M("unlock ob", 'orders_', C('DB_CONFIG2'))
            ->join("orders o on o.id = ob.oid")
            ->join("system_user u on u.id = o.user_id")
            ->where(implode($where,' AND '))->count();
        $page = $this->page( $count, 20 );
        $list = M("unlock ob", 'orders_', C('DB_CONFIG2'))
            ->field('o.id,o.loan_time,u.name,u.identity,o.loan_day,o.stages,u.account_status,o.status,o.loan_user,u.is_adult,
            ob.amount,ob.principal')
            ->join("orders o on o.id = ob.oid")
            ->join("system_user u on u.id = o.user_id")
            ->where(implode($where,' AND '))->order("o.loan_time DESC")
            ->limit($page->firstRow.','.$page->listRows)
            ->select();
        $this->assign("page", $page->show('Admin'));

        //合计
        $for_total = M("unlock ob", 'orders_', C('DB_CONFIG2'))
            ->field('SUM(ob.amount) AS total_amount,SUM(ob.principal) AS total_bond_amount')
            ->join("orders o on o.id = ob.oid")
            ->join("system_user u on u.id = o.user_id")
            ->where(implode($where,' AND '))
            ->find();
        $this->assign('total',$for_total);
        $this->assign('list',$list);
        $this->display();
    }
}
